<template>
    <transition
        enter-active-class="animate__animated animate__fadeInUp animate__faster"
        leave-active-class="animate__animated animate__zoomOut animate__faster">
             <div class='scrollTop' :style="'right:'+right" v-if="topState" @click="gotop"></div>
    </transition>
</template>

<script>
    export default {
        name: "scrollTop",
        components: {},
        props:{
              //  指定需要滚动的元素
              scrollEl:{
                  type:String,
                  default:''
              },
              right:{
                  type:String,
                  default:'.32rem'
              }

        },
        data() {
            return {
                topState:false,
                top:0,
                parentEl:null
            }
        },
        created() {
        },
        mounted(){
            let parentEl =this.$parent.$el;
            if(this.scrollEl){
                parentEl = this.$parent.$refs[this.scrollEl]
            }
            parentEl.addEventListener('scroll',this.scroll)
            this.parentEl = parentEl
        },
        destroyed() {
            this.parentEl.removeEventListener("scroll", this.scroll);
        },
        methods:{
            // 滚动事件
            scroll (e) {
                this.top = e.target.scrollTop;
                if(this.top > 120){
                    this.topState = true
                }else{
                    this.topState = false
                }
            },
            // 回到顶部
            gotop () {
                let timer = setInterval(() => {
                    this.parentEl.scrollTop  = this.top - 90
                    if (this.top === 0) {
                        clearInterval(timer)
                    }
                }, 15)
            },
        }
    }
</script>
<style scoped lang='scss'>
$icnBg:'../../assets/images/top.png';
@media screen and (min-width:960px) and (max-width:1920px){
    .scrollTop{
        @include boxBase(42px,42px);
        @include background($icnBg,transparent);
        position: fixed;
        right: 28px;
        bottom: 58px;
        cursor: pointer;
    }
}
@media screen and (max-width:959px){
    .scrollTop{
        @include boxBase(1.12rem,1.12rem);
        @include background($icnBg,transparent);
        position: fixed;
        right: .32rem;
        bottom: 1.546rem;

    }
}


.icon{
    @include boxBase()
}
</style>
